package com.mfy.controller;


import com.mfy.entity.Admin;
import com.mfy.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mfy
 * @since 2023-05-08
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Resource
    //获取RedisTemplate工具
    private RedisTemplate<String,Object> redisTemplate;
    /**用户登录*/
    @PostMapping("/tokens")
    public Map<String,String> tokens(@RequestBody Admin admin, HttpSession session) {
        Map<String, String> result = new HashMap<>();
        //转json,fastjson有安全漏洞 推荐用jackson
        //log.info("接受到admin对象为:{}", JSONUtils.writeJSON(admin));
        // 登录
        Admin adminDB = adminService.login(admin);
        // 登录成功,获取token
        String token = session.getId();
        redisTemplate.opsForValue().set(token,adminDB,30, TimeUnit.MINUTES);
        result.put("token",token);
        return result;
    }

    @GetMapping("/admin-user")
    public Admin userinfo(String token){
        return (Admin)redisTemplate.opsForValue().get(token);
    }

    //登出
    @DeleteMapping("/tokens/{token}")
    public void logout(@PathVariable("token")String token){
        redisTemplate.delete(token);
    }
}

